var map;
var marker;

var locations2 = [
	['Golf de guinée', -13.890542, -1.274856, 4],
	['Tunis', 36.923036, 10.259052, 5],
	['Roumanie', 54.028249, 51.157507, 3],
	['Sibérie', 63.80010128657071, 141.28747820854187, 2],
	['Malésie', -2.750198, 102.259302, 1]
];
$longitude = 0;
$latitude = 0;
var maerker, i;
var infowindow;
var watchID;
var urli = encodeURI("http://bleach-en-ligne.fr/cordova/upload.php");

$(document).ready(function(){
	document.addEventListener("deviceready", onDeviceReady, false);
});

//Cordova is ready function
function onDeviceReady() {
	$("#home").on('swiperight', swipeMap);
	$("#home").on('swipeleft', swipeUpload);
	$("#mapping").on('swipeleft', swipeHome);
	$("#uploading").on('swiperight', swipeHome2);
	$("#map").on('swipeleft', function(){ return false; });
	$(document).on('pageshow', '#mapping', LoadMap);
	$(document).on('pageshow', '#uploading', LoadHome);
}

function swipeHome() {
	$.mobile.changePage("#home", {
		allowSamePageTransition : true,
		transition : 'slide',
		reloadPage : false
		});
}
function swipeHome2() {
	$.mobile.changePage("#home", {
		allowSamePageTransition : true,
		reverse : true,
		transition : 'slide',
		reloadPage : false
		});
}
function swipeUpload() {
	$.mobile.changePage("#uploading", {
		allowSamePageTransition : true,
		transition : 'slide',
		reloadPage : false
		});
}
function swipeMap() {
	$.mobile.changePage("#mapping", {
		allowSamePageTransition : true,
		reverse : true,
		transition : 'slide',
		reloadPage : false
		});
}

function LoadHome(){
	$('#loaders').html('Chargement de votre position actuelle... ');
	watchID = navigator.geolocation.getCurrentPosition(camera_success, geo_error, { maximumAge: 300000, timeout: 30000, enableHighAccuracy: true }); 
}
function camera_success(position){
	$('#loaders').empty();
	$longitude = position.coords.longitude;
	$latitude = position.coords.latitude;
	LoadCamera();
}

function LoadCamera(){
	navigator.camera.getPicture(onSuccess, onFail, {
		quality: 50,
		destinationType: Camera.DestinationType.FILE_URI,
		saveToPhotoAlbum : true,
		targetWidth: 720,
		correctOrientation: true
	});
}
function onSuccess(imageURI) {
	$divImage = $('#myImage');
	$img = $('<img>');
	$divImage.append($img);
	$img.attr('src', imageURI);
	uploadPhoto(imageURI);
}
function onFail(message) {
	//alert('Failed because: ' + message);
	alert('Prise de photo avortée !');
}


function LoadMap() {
	$(window).unbind();
	$(window).bind('pageshow resize orientationchange', function(e){
		max_height();
	});
	max_height();
	google.load("maps", "3", {"callback": map, other_params: "sensor=true"});
}

function max_height(){
	var h = $('div[data-role="header"]').outerHeight(true);
	var f = $('div[data-role="footer"]').outerHeight(true);
	var w = $(window).height();
	var c = $('div[data-role="content"]');
	var c_h = c.height();
	var c_oh = c.outerHeight(true);
	//var c_new = w - h - f - c_oh + c_h;
	var c_new = w * 80 / 100;
	var total = h + f + c_oh;
	if(c_h<c.get(0).scrollHeight){
		c.height(c.get(0).scrollHeight);
	}else{
		c.height(c_new);
	}
}

function map(){
	var latlng = new google.maps.LatLng(48.50, 2.20); //Paris centered
	var myOptions = {
		zoom: 5,
		//zoom: 5 to see all france
		center: latlng,
		streetViewControl: true,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		zoomControl: true
	};
	map = new google.maps.Map(document.getElementById("map"), myOptions);

	google.maps.event.addListenerOnce(map, 'tilesloaded', function(){
		watchID = navigator.geolocation.getCurrentPosition(geo_success, geo_error, { maximumAge: 30000, timeout: 30000, enableHighAccuracy: true }); 
		//watchID = navigator.geolocation.watchPosition(geo_success, geo_error, { maximumAge: 10000, timeout: 10000, enableHighAccuracy: true });  
	});
}

function geo_error(error){
	//comment
	alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
}

function geo_success(position) {
	map.setCenter(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
	//map.setZoom(12);

	var info =
	('Latitude: '         + position.coords.latitude          + '<br>' +
	'Longitude: '         + position.coords.longitude         + '<br>' +
	'Altitude: '          + position.coords.altitude          + '<br>' +
	'Accuracy: '          + position.coords.accuracy          + '<br>' +
	'Altitude Accuracy: ' + position.coords.altitudeAccuracy  + '<br>' +
	'Heading: '           + position.coords.heading           + '<br>' +
	'Speed: '             + position.coords.speed             + '<br>' +
	'Timestamp: '         + new Date(position.timestamp));

	var point = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

	if(!marker){
		//create marker
		marker = new google.maps.Marker({
			position: point,
			map: map
		});
	}else{
		//move marker to new position
		marker.setPosition(point);
	}
	if(!infowindow){
		infowindow = new google.maps.InfoWindow({
			content: info
		});
	}else{
		infowindow.setContent(info);
	}
	google.maps.event.addListener(marker, 'click', function() {
		infowindow.open(map,marker);
	});
	drawCircle(marker);

	setTimeout( function(){ displayMarkers(locations2) ; }, 5000);
}

function displayMarkers(loca){
	for (i = 0; i < loca.length; i++) {
		maerker = new google.maps.Marker({
			position: new google.maps.LatLng(loca[i][1], loca[i][2]),
			map: map
		});
		drawCircle(maerker);
		google.maps.event.addListener(maerker, 'click', (function(maerker, i) {
			return function() {
				infowindow.setContent(loca[i][0]);
				infowindow.open(map, maerker);
			}
		})(maerker, i));
	}
}

function drawCircle(m){
	var circle = new google.maps.Circle({
	map: map,
	radius: 100000,    // 10 miles in metres
	fillColor: '#AA0000',
	strokeOpacity : 0
	});
	circle.bindTo('center', m, 'position');
}

function uploadPhoto(imageURI) {
	var options = new FileUploadOptions();
	options.fileKey="file";
	options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
	options.mimeType="image/jpeg";

	var params = {
		img : options.fileName,
		longitude : $longitude,
		latitude : $latitude
	}

	options.params = params;

	var ft = new FileTransfer();
	ft.upload(imageURI, urli, win, fail, options);
}

function win(r) {
	alert('upload.php called!');
	console.log("Code = " + r.responseCode);
	console.log("Response = " + r.response);
	console.log("Sent = " + r.bytesSent);
}

function fail(error) {
	alert("An error has occurred: Code = " + error.code);
	console.log("upload error source " + error.source);
	console.log("upload error target " + error.target);
}